/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useRef, useState, useMemo, useCallback, useEffect } from 'react';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import { Button, Form, Select, Space, Row, Col, message } from 'antd';
import styles from './index.less';
import {
  cardSpan,
  commonInputStyle,
  formSpan,
  formTextColumns,
  formUploadImageColumns,
} from './utils';
import { useSelector } from 'umi';
import type { ConnectState } from '@/models/connect';
import UploadImage from './uploadImage';
import type { FormValuesType, StringObjType } from './index.d';
import { getCheckAccount, submitApply } from '@/services/amountApply';
import { isEmpty } from 'lodash';
import CheckAccountInfo from './checkAccountInfo';
const { Option } = Select;

interface PropsType {
  renewalApplyInfo: StringObjType;
  renewalApply: (data: StringObjType) => void;
}
const ApplyForm: React.FC<PropsType> = (props) => {
  const { renewalApplyInfo, renewalApply } = props;
  const formRef = useRef<ProFormInstance>();
  const [formValues, setFormValues] = useState<FormValuesType>({});
  const [checkAccountInfo, setCheckAccountInfo] = useState<StringObjType>({});

  const { winSize } = useSelector((state: ConnectState) => state.global);
  const isMobile = winSize === 'xs';

  useEffect(() => {
    if (!isEmpty(renewalApplyInfo)) {
      formRef.current?.setFieldsValue(renewalApplyInfo);
      setFormValues(renewalApplyInfo);
    }
  }, [renewalApplyInfo]);

  // 检查账号信息按钮
  const checkAccountButton = useMemo(() => formValues.mobile?.length == 11, [formValues]);

  const onFormChange = () => {
    const values = formRef.current?.getFieldsValue();
    setFormValues({ ...values });
  };

  // 手机号变动需要重新验证
  useEffect(() => {
    setCheckAccountInfo({});
  }, [formValues.mobile]);

  const onReset = () => {
    formRef.current?.resetFields();
    onFormChange();
    setCheckAccountInfo({});
    renewalApply({});
  };
  const onFinish = async (params: StringObjType) => {
    if (isEmpty(checkAccountInfo)) {
      message.error('请先验证账号');
      return;
    }

    const { code } = await submitApply({ ...params });
    if (code == 0) {
      onReset();
    }
  };
  // 验证账号信息
  const onCheckAccount = useCallback(async () => {
    const { mobile } = formValues;
    const { data } = await getCheckAccount({ mobile });
    if (data?.alipay_account) {
      formRef.current?.setFieldsValue({
        account: data?.alipay_account,
      });
    }
    setCheckAccountInfo(data);
  }, [formValues]);

  return (
    <ProForm
      className={isMobile ? styles.proForm : styles.main}
      formRef={formRef}
      onFinish={onFinish}
      layout='horizontal'
      initialValues={{
        type: 'courier',
      }}
      submitter={false}
      labelCol={{ span: 5 }}
      onChange={onFormChange}
    >
      <Row>
        <Col {...formSpan}>
          <ProFormText
            className={styles.menu_input}
            label='请查询类型类型'
            name='mobile'
            addonBefore={
              <Form.Item name='type' noStyle>
                <Select style={{ width: 100 }}>
                  <Option value='courier'>快递员</Option>
                  <Option value='dak'>驿站</Option>
                </Select>
              </Form.Item>
            }
            addonAfter={
              <Button type='primary' disabled={!checkAccountButton} onClick={onCheckAccount}>
                账号信息检测
              </Button>
            }
            fieldProps={{
              style: commonInputStyle,
            }}
            placeholder='请输入手机号'
            rules={[
              {
                required: true,
                message: '请输入手机号',
              },
            ]}
          />
          {formTextColumns.map((item: StringObjType) => (
            <ProFormText
              key={item.name}
              fieldProps={{
                style: commonInputStyle,
              }}
              rules={[
                {
                  required: true,
                  message: item.placeholder,
                },
              ]}
              {...item}
            />
          ))}

          {formUploadImageColumns.map((item) => (
            <Form.Item
              key={item.name}
              rules={[
                {
                  required: true,
                  message: '请上传' + item.defaultText,
                },
              ]}
              name={item.name}
              label={item.label}
            >
              <UploadImage defaultText={item.defaultText} />
            </Form.Item>
          ))}
          <Form.Item label={' '} colon={false} noStyle={isMobile}>
            <div style={{ color: 'red' }}>
              注：
              <br />
              1.
              纸质证明：企业请上传营业执照；私人，请上传申请书面材料（内容包含：姓名、身份证号、提现金额及账号、时间、手印）
              <br />
              2. 人像、身份证、纸质证明要清晰可见
              <br />
            </div>
          </Form.Item>
        </Col>
        <Col {...cardSpan} offset={isMobile ? 0 : 1}>
          <CheckAccountInfo data={checkAccountInfo} />
        </Col>
      </Row>
      <Form.Item colon={false} label=' ' labelCol={{ span: 3 }}>
        <Space>
          <Button type='primary' onClick={() => formRef?.current?.submit?.()}>
            提交
          </Button>
          <Button onClick={onReset}>重置</Button>
        </Space>
      </Form.Item>
    </ProForm>
  );
};

export default ApplyForm;
